var Q = require('q'),
    operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    BaseFun = require('../../../Base/server/controllers/Function'),
    BaseEnum = require('../../../Base/server/controllers/Enum'),
    workController = require('../../../CBO/server/controllers/Work.server.controller'),
    enumController = require('../../../QC/server/controllers/Enum.server.controller'),
    extendEnumController = require('../../../Common/server/controllers/ExtendEnum.server.controller');

//标签打印添加
exports.submitTagPrint = function (req, res) {
    var parameter = req.body.Parameter,
        barcodeData = parameter.barcodeData,
        Terminal = parameter.Terminal,
        TerminalName = parameter.TerminalName,
        Work = parameter.Work,
        WorkName = parameter.WorkName,
        WorkLocation = parameter.WorkLocation,
        WorkLocationName = parameter.WorkLocationName,
        userId = parameter.userId;

    var dateNow = Date.now(),
        bizRecord = {
            CollectDateTime: dateNow,
            Users: [userId]   
        };

    var transactions = [];//保存事务的

    //根据物料和作业查找工序
    queryOperation(barcodeData.ItemMaster, Work).then(function(operationRecord) {
        //新增流水
        bizRecord.BarcodeMaster = barcodeData._id;
        bizRecord.Work = Work;
        bizRecord.WorkName = WorkName;
        bizRecord.WorkLocation = WorkLocation;
        bizRecord.WorkLocationName = WorkLocationName;
        bizRecord.Terminal = Terminal;
        bizRecord.TerminalName = TerminalName;
        bizRecord.Operation = operationRecord._id;
        bizRecord.OperationName = operationRecord.Name;
        bizRecord._id = BaseFun.getObjectId();
        bizRecord.RowStatus = BaseEnum.RowStatus.Insert.Value;
        bizRecord.CreatedBy = userId;      
        transactions.push({
            EntityName: 'BizRecord',
            Records: [bizRecord]
        });
        //更新主档
        var updateRecord = {
            Users: bizRecord.Users,
            BizRecord: bizRecord._id,
            Work: bizRecord.Work,
            WorkName: bizRecord.WorkName,
            WorkLocation: bizRecord.WorkLocation,
            WorkLocationName: bizRecord.WorkLocationName,
            Terminal: bizRecord.Terminal,
            TerminalName: bizRecord.TerminalName,
            Operation: bizRecord.Operation,
            OperationName: bizRecord.OperationName,
            RowStatus: BaseEnum.RowStatus.Modify.Value,
            CreatedBy: userId,
            _id: bizRecord.BarcodeMaster,
            SysVersion: barcodeData.SysVersion
        };
        transactions.push({
            EntityName: 'BarcodeMaster',
            Records: [updateRecord]
        });
        return Q.nfcall(Transaction.BatchSaveByTran, transactions);
    }).then(function() {
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function(err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};



//标签打印更新
exports.updateTagPrint = function (req, res) {
    var parameter = req.body.Parameter,
        barcodeData = parameter.barcodeData,
        userId = parameter.userId;
        
    var dateNow = Date.now();
    var updatebizRecord = {
        Users: [userId],
        CollectDateTime: dateNow,
        RowStatus: BaseEnum.RowStatus.Modify.Value,
        CreatedBy: userId,
        _id: barcodeData.BizRecord._id,
        SysVersion: barcodeData.SysVersion
    };
    var transactions = [];
    transactions.push({
        EntityName: 'BizRecord',
        Records: [updatebizRecord]
    });
                            
    Q.nfcall(Transaction.BatchSaveByTran, transactions).then(function () {
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function(err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
    
};



//根据物料和作业查找工序
function queryOperation(itemMaster, work) {
    var deferred = Q.defer();

    if (!itemMaster) {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.message = '主档未绑定物料';
        deferred.reject(newErr);
        return;
    }
    operationController.findByItemMasterAndWork(itemMaster, work, function(err, result) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (!result) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '非法数据';
            newErr.message = '没有找到对应的工序';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(result);
    });

    return deferred.promise;
}

